import myspace.app

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from oauthlib.oauth import OAuthError
from entities import WinLoss

class WebService(webapp.RequestHandler):
  def get(self):
    id = self.request.get('id')
    
    try:
        int(id)
    except:
        error = {'errorCode':'invalidInput','errorMessage':'Invalid ID'}
        self.response.out.write(simplejson.dumps(error))
        return
    
    key = db.Key.from_path('WinLoss', 'id_' + id)
    wl = db.get(key)
    
    if wl is None:
        error = {'errorCode':'inputNotFound','errorMessage':'ID not found'}
        self.response.out.write(simplejson.dumps(error))
        return
    else:
        success = {'wins':wl.wins,'losses':wl.losses}
        self.response.out.write(simplejson.dumps(success))
    

  def post(self):
    debug = False
    
    if debug is True:
        output = ''
        params = self.request.GET
        for p in params:
            output += p + '=' + params[p] + '&'
        
        self.response.out.write(simplejson.dumps(output))
        return  

    id = self.request.get('id')
    win = self.request.get('win')
    
    try:
        int(id)
    except:
        error = {'errorCode':'invalidInput','errorMessage':'Invalid ID'}
        self.response.out.write(simplejson.dumps(error))
        return
    
    qs = self.request.GET
    secret = '349782a9c39846e2b216ccb078a2db7c'
    method = 'POST'
    url = 'http://opensocial--tic-tac-toe.appspot.com/ws'
    key = 'http://www.myspace.com/459809216'
    
    try:
        valid = myspace.app.verify_request(key, secret, method, url, qs)
    except OAuthError, mse:
        self.response.out.write(simplejson.dumps({'error':mse.message})) 
        return

    if valid is False:
        error = {'errorCode':'invalidInput','errorMessage':'Invalid sig.'}
        self.response.out.write(simplejson.dumps(error))
        return

    key = db.Key.from_path('WinLoss', 'id_' + id)
    wl = db.get(key)
    
    if wl is None:
        wl = WinLoss(wins=0,losses=0,key_name='id_'+id)
    
    if win:
        wl.wins += 1
    else:
        wl.losses += 1
        
    wl.key_name = id
    wl.put()
    
    success = {'success':'Record updated','wins':wl.wins,'losses':wl.losses}
    self.response.out.write(simplejson.dumps(success))

def main():
  application = webapp.WSGIApplication([
    ('/ws', WebService),
    ], debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()